package io.noties.markwon.app.samples.html;


import com.noties.markwon.wrapper.text.style.URLSpan;
import io.noties.markwon.Markwon;
import io.noties.markwon.MarkwonVisitor;
import io.noties.markwon.app.sample.Tags;
import io.noties.markwon.app.sample.ui.MarkwonTextViewSample;
import io.noties.markwon.html.HtmlPlugin;
import io.noties.markwon.html.HtmlTag;
import io.noties.markwon.html.MarkwonHtmlRenderer;
import io.noties.markwon.html.TagHandler;
import io.noties.markwon.sample.annotations.MarkwonArtifact;
import io.noties.markwon.sample.annotations.MarkwonSampleInfo;
import java.util.Collection;

@MarkwonSampleInfo(
        id = "20210201140501",
        title = "Inspect text",
        description = "Inspect text content of a `HTML` node",
        artifacts = {MarkwonArtifact.HTML},
        tags = {Tags.html}
)
public class InspectHtmlTextSample extends MarkwonTextViewSample {

    @Override
    public void render() {
        String md = "<p>lorem ipsum</p>\n" +
                "<div class=\"custom-youtube-player\">https://www.youtube.com/watch?v=abcdefgh</div>";
        Markwon markwon = Markwon.builder(context)
                .usePlugin(HtmlPlugin.create((it) -> {
                    it.addHandler(new DivHandler());
                }))
                .build();

        markwon.setMarkdown(textView, md);

    }

    class DivHandler extends TagHandler {
        @Override
        public void handle(MarkwonVisitor visitor, MarkwonHtmlRenderer renderer, HtmlTag tag) {
            String attr = tag.attributes().get("class");
            if (attr == null) {
                return;
            }
            if (attr.contains(CUSTOM_CLASS)) {
                String text = visitor.builder().toString().substring(tag.start(), tag.end());
                visitor.builder().setSpan(
                        new URLSpan(text),
                        tag.start(),
                        tag.end()
                );
            }

        }

        @Override
        public Collection<String> supportedTags() {
            return null;
        }
    }

    private static final String CUSTOM_CLASS = "custom-youtube-player";
}
